package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _40二叉树的直径
 * @description
 * @date 2023/06/15 21:57
 * <p>
 * ******************************************************
 */
public class _40二叉树的直径 {

    int max = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        diameter(root);
        return max;
    }

    private int diameter(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = diameter(root.left);
        int right = diameter(root.right);
        int curr = left + right;
        max = Math.max(curr, max);
        return Math.max(left, right) + 1;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
